<?php
namespace app\agent\controller;
use think\Controller;
use think\Db;
use app\common\controller\AgentBaseController;
use app\agent\model\GoodsModel;
use app\common\model\Shopping;
use app\common\model\Order;
class Shop extends AgentBaseController
{
	
	protected function _initialize() {
        parent::_initialize();
		//新用户送鼓励金数量
		if(!empty(input('good_id'))){
			session('buy_good_id',input('good_id'));
		}

		//receive();
    }
	//批量导入商品
	public function export_goods(){
		return $this->fetch();
	}
	//批量导入商品
	public function export_ruku(){
		return $this->fetch();
	}
	public function padd_ok(){
		$fileName = 'public/upload/'.$_FILES['myfile']['name'];
		$arr_sql=dr($fileName);
		$f=array();
		$where['agent_id']=session('agent_id');
		$r=$arr_sql[0];
		$r=explode(',', $r);
		if($r[0]=="id"){
			$list;
			for($i=1;$i<count($arr_sql);$i++){
				$row=$arr_sql[$i];
				$row=explode(',', $row);
				$data['id']=$row['0'];
				$data['goods_no']=trim($row['1']);
				$data['goods_name']=$row['2'];
				$where['type_name']=trim($row['3']);
				$type=db('agent_type')->field("id")->where($where)->find();
				$data['trade_id']=$type['id'];
				$data['cost_price']=$row['4'];
				$data['sale_price']=$row['5'];
				$data['zs_price']=$row['6'];
				$data['dk_price']=$row['5']-$row['7'];
				$data['stock']=$row['8'];
				$data['is_recommend']=$row['9'];
				$data['chainstore_id']=$row['11'];
				$list[]=$data;
			}
			$p=implode(',', $f);
			if($list){
				Db::startTrans();
				$gd_model=new GoodsModel();
				$res=$gd_model->saveAll($list);
				if($res){
					Db::commit();
			 		$this->success('批量导入成功', url('goods_manage',['p'=>1]));
			 	}else{
			 		Db::rollback();
	        		$this->success('批量导入失败' , url('goods_manage',['p'=>1]));
				}
			}else{
				$this->success('批量导入失败' , url('goods_manage',['p'=>1]));
			}
		}else{
			for($i=1;$i<count($arr_sql);$i++){
				$row=$arr_sql[$i];
				$row=explode(',', $row);
				$data[$i-1]['goods_no']=trim($row['0']);
				$data[$i-1]['goods_name']=$row['1'];
				$where['type_name']=trim($row['2']);
				$type=db('agent_type')->field("id")->where($where)->find();
				$data[$i-1]['trade_id']=$type['id'];
				$data[$i-1]['cost_price']=$row['3'];
				$data[$i-1]['sale_price']=$row['4'];
				$data[$i-1]['zs_price']=$row['5'];
				$data[$i-1]['dk_price']=$row['4']-$row['6'];
				$data[$i-1]['stock']=$row['7'];
				$data[$i-1]['is_recommend']=$row['8'];
				$data[$i-1]['content']=$row['9'];
				$data[$i-1]['chainstore_id']=$row['10'];
				$data[$i-1]['agent_id']=session('agent_id');
				$data[$i-1]['oem_id']=session('oem_id');
				$data[$i-1]['addtime']= date("Y-m-d H:i:s");
			}
			$p=implode(',', $f);
			$data=isset($data)?$data:"";
			if($data){
				Db::startTrans();
				if(Db::name('agent_goods')->insertAll($data)){
					Db::commit();
			 		$this->success('批量导入成功', url('goods_manage',['p'=>1]));
			 	}else{
			 		Db::rollback();
	        		$this->success('批量导入失败' , url('goods_manage',['p'=>1]));
				}
			}else{
				$this->success('批量导入失败' , url('goods_manage',['p'=>1]));
			}
		}
	}
	//批量入库
	public function padd_ok1(){
		$file = request()->file('myfile');  
        $info = $file->validate(['ext' => 'xlsx,xls'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'baoming');  
  
        //数据为空返回错误  
        if(empty($info)){  
            $output['status'] = false;  
            $output['info'] = '导入数据失败~';  
           echo "导入失败";exit;
        } 
		 //获取文件名  
        $exclePath = $info->getSaveName();  
        //上传文件的地址  
        $filename = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'baoming'. DS . $exclePath;  
  		import("PHPExcel.PHPExcel");
        //判断截取文件  
        $extension = strtolower( pathinfo($filename, PATHINFO_EXTENSION) );  
        //区分上传文件格式  
        if($extension == 'xlsx') {  
            $objReader =\PHPExcel_IOFactory::createReader('Excel2007');  
            $objPHPExcel = $objReader->load($filename, $encode = 'utf-8');  
        }else if($extension == 'xls'){  
            $objReader =\PHPExcel_IOFactory::createReader('Excel5');  
            $objPHPExcel = $objReader->load($filename, $encode = 'utf-8');  
        }  
		$where['agent_id']=session('agent_id');
		$excel_array = $objPHPExcel->getsheet(0)->toArray();   //转换为数组格式
        $res = [];  
		Db::startTrans();
        foreach($excel_array as $k=>$v) {
        	if($k>0){
        		 $where['goods_no']=NumToStr(trim($v[0]));
				$up['stock']=['exp','stock+'.$v[1]];
				$goods_id=db('agent_goods')->where($where)->value("id");
				$result=db('agent_goods')->where($where)->update($up);
				if(!$result){
					Db::rollback();
					$this->success('批量导入失败'.$goods_id , url('goods_manage',['p'=>1]));
				}
				$data['add_time']=now_time();
				$data['goods_id']=$goods_id;
				$data['agent_id']=session("agent_id");
				$data['nums']=$v[1];
				$result=db('agent_ruku')->insert($data);
				if(!$result){
					Db::rollback();
					$this->success('批量导入失败' , url('goods_manage',['p'=>1]));
				}
        	}
           
        }  
		
		Db::commit();
	 	$this->success('批量导入成功', url('goods_manage',['p'=>1]));
		
	}
	//处理商品批量上下架 推荐
	public function chuli($status){
		if($status==3){
			$up['is_recommend']=1;
		}elseif($status==4){
			$up['is_recommend']=2;
		}elseif($status==5){
			$up['goods_state']=3;
		}else{
			$up['goods_state']=$status;
		}
		$where['id']=["in",input()['arr']];
		$res=db("agent_goods")->where($where)->update($up);
		if($res){
			return json(['code'=>200,'msg'=>'操作成功']);
		}else{
			return json(['code'=>400,'msg'=>'操作失败']);
		}
	}
	public function goods_code(){
		$goods = db('agent_goods')->find(input("goods_id"));
    	$agent_store = db('info_agent')->find($goods['agent_id']);
    	$code_url="https://".$_SERVER['HTTP_HOST']."/agent/shop/fast_buy?good_id=".$goods['id'];
    	
    	$agent_info['code_url'] = $code_url;
    	$agent_info['goods_name'] = $goods['goods_name'];
    	$agent_info['agent_name'] = $agent_store['agent_name'];
    	$agent_info['logo'] = $goods['thumb'];
    	$this->assign('agent_info',$agent_info);
		$chains=db("agent_store")->field("id,store_name")->where('agent_id',$goods['agent_id'])->select();
		$this->assign("chains",$chains);
    	return $this->fetch();
	}
	public function down_zip(){
		$agent_id=session('agent_id');
		$datalist=array();
		$filename = "././public/upload/{$agent_id}_goods.zip";
		$length=input("length");
		if(file_exists($filename)){
			unlink($filename);
		}
		 $zip = new \ZipArchive();
		 if ($zip->open($filename, \ZipArchive::CREATE)==TRUE) {
		  for( $i=0;$i<$length;$i++){
		  	$s=$agent_id."_".$i;
		  	$val="././public/upload/".$s.".png";
		   if(file_exists($val)){
		    $zip->addFile( $val, basename($val));
		   }
		  }
		  $zip->close();
		 }
		
		if(!file_exists($filename)){
		 exit("无法找到文件");
		}
		header("Cache-Control: public");
		header("Content-Description: File Transfer");
		header('Content-disposition: attachment; filename='.basename($filename)); //文件名
		header("Content-Type: application/zip"); //zip格式的
		header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
		header('Content-Length: '. filesize($filename)); //告诉浏览器，文件大小
		@readfile($filename);
	}
	public function export_img(){
		$imgs=input()['imgs'];
		$agent_id=session('agent_id');
		foreach($imgs as $k=>$v){
			$s=$agent_id."_".$k;
			$path="././public/upload/".$s.".png";
			$this->base64_image_content($v, $path);
		}
		exit;
		
		//var_dump($_POST);exit;
	}
	function base64_image_content($base64_image_content,$path){
	    //匹配出图片的格式
	    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
	        $type = $result[2];
	//      if(!file_exists($new_file)){
	//          //检查是否有该文件夹，如果没有就创建，并给予最高权限
	//          mkdir($new_file, 0700);
	//      }
	        if (file_put_contents($path, base64_decode(str_replace($result[1], '', $base64_image_content)))){
	            return '/'.$path;
	        }else{
	            return false;
	        }
	    }else{
	        return false;
	    }
	}
	//批量修改门店
	function select_store(){
		
		$id_list = input('id_list');
		if($_POST){
			//获取门店id
			$chain_id = input('chain_id');
			$id_list = explode(",",$id_list);
			$where['id'] = ['in',$id_list];
			$resutl = db('agent_goods')->where($where)->update(['chainstore_id' => $chain_id]);
			if($resutl){
				return json(["code"=>200,'msg'=>'更新成功']);
			}else{
				return json(["code"=>403,'msg'=>'修改失败']);
			}
		}
		
		$chains=db("agent_store")
				->field("id,store_name")
				->where('agent_id',session('agent_id'))
				->where('state',1)
				->select();
		$this->assign("id_list",substr($id_list,0,strlen($id_list)-1));
		$this->assign("chains",$chains);
		return $this->fetch();
	}
	
	//批量修改分类
	function select_sort(){
		$id_list = input('id_list');
		if($_POST){
			//获取门店id
			$sort_id = input('sort_id');
			$id_list = explode(",",$id_list);
			$where['id'] = ['in',$id_list];
			$resutl = db('agent_goods')->where($where)->update(['trade_id' => $sort_id]);
			if($resutl){
				return json(["code"=>200,'msg'=>'更新成功']);
			}else{
				return json(["code"=>403,'msg'=>'修改失败']);
			}
		}
		
		$chains=db("agent_type")->field("id,type_name")->where('agent_id',session('agent_id'))->select();
		$this->assign("id_list",substr($id_list,0,strlen($id_list)-1));
		$this->assign("chains",$chains);
		return $this->fetch();
	}
	
	
	public function down_qr_code(){
		//获取当前商家信息
		$goods_id = input('id');
		$goods_id = substr($goods_id,0,strlen($goods_id)-1);
		$arr_id = explode(",", $goods_id); 
		
		$goods_arr = array();
		if(count($arr_id)>0){
			for($i=0;$i<count($arr_id);$i++){
				//获取商品信息
				$goods_info = db('agent_goods')->where('id',$arr_id[$i])->find();
				$code_url="http://".$_SERVER['HTTP_HOST']."/agent/shop/fast_buy?good_id=".$arr_id[$i];
				$goods_info['code_url'] = $code_url;
				array_push($goods_arr,$goods_info);
			}
		}else{
			return json(["code"=>403,'msg'=>'请选择商品']);
		}
		//获取商家信息
		$agent_info = db('info_agent')->find(session('agent_id'));
		//商家所有门店
		$chains=db("agent_store")->field("id,store_name")->where('agent_id',$agent_info['id'])->select();
		
		$this->assign('agent_info',$agent_info);
		$this->assign("chains",$chains);
		$this->assign("goods_arr",$goods_arr);
		
    	return $this->fetch();
	}
	
	//单产品快速付款页面
	public function fast_buy(){
		$good_id=input('good_id');
		$type=get_brower_type();//判断是微信还是支付宝打开
		$user=session("info_user");
		$goods=db('agent_goods')->where("id",$good_id)->find();
		if(!session('openid')){
			$redirect='https://'.$_SERVER['HTTP_HOST'].'/agent/shop/fast_buy?good_id='.$good_id;
			if($type==1){
				$auth_code=input("auth_code");
				$url ='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.config('alipay_appid').'&scope=auth_base&redirect_uri='.urlencode($redirect);
			}else{
				$auth_code=input("code");
				$url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect';
			}
			if(!$auth_code){
				Header("Location: $url");
				exit;
			}
			
		    $openid = '';
			if($type==1){//支付宝openid
				$field="alipay_id";
				$pay_type=3;
				$openid=user_ali_id($auth_code);
			}elseif($type==2){//微信openid
				$field="openid";
				$pay_type=2;  
				$openid=user_wx_id($auth_code);
			}	
			session('openid',$openid);
			$user_info = db('info_user')->where($field,$openid)->find();
            if($user_info){
                session('info_user', $user_info);
            }else{
            	$agent_uid=db('info_agent')->where('id',$goods['agent_id'])->value("user_id");
				$tj_user_info = db('info_user')->where('id',$agent_uid)->find();
				    $data['level']			= $tj_user_info['id'];
                    $data[$field]			= $openid;
					$data['oem_id']			= $tj_user_info['oem_id'];
					$data['agency_id']		= $tj_user_info['agency_id'];
                    $data['agency_id1']		= $tj_user_info['agency_id1'];
                    $data['agency_id2']		= $tj_user_info['agency_id2'];
                    $data['salesman_id']	= $tj_user_info['salesman_id'];
                    $data['tj_pt']			= $tj_user_info['tj_pt'];
					$data['tj_pt1']			= $tj_user_info['tj_pt1'];
					$data['tj_agent']		= $tj_user_info['tj_agent'];
					$data['member_level']	= "ratio_one";
                    $data['add_time']		= now_time();
                    $data['reg_type']		= 6;//6单商品
					$user_id=Db::name('info_user')->insertGetId($data);
                    $cut_user_info = db('info_user')->where('id',$user_id)->find();
                    //获取用户信息
                    session('info_user', $cut_user_info);
                    if($type==2){
						receive();
					}      
            }	
		}

		$user = db('info_user')->where('id',session("info_user")['id'])->find();
		$this->assign("goods",$goods);
		$this->assign("score",$user['score']);  
	 
        //模拟数据
		if($type==1){
			return $this->fetch("fast_buy1");
		}else{
			return $this->fetch();
		}	
	}

	public function ad_del(){
		$result = Db::table('agent_advertisement')->where('id',input("id"))->delete();
		if($result){
			return json(["code"=>200,'msg'=>'操作成功']);
		}else{
			return json(["code"=>400,'msg'=>'操作失败']);
		}
	}

	public function ad_edit(){
		if($_POST){
			$update['url']=input("url");
			$update['add_time']=now_time();
			$update['title']=input("title");
			$update['thumb']=input("logo");
			$update['agent_id']=session('agent_id');
			$res=db("agent_advertisement")->where("id",input("id"))->update($update);
		}
		$ad=db("agent_advertisement")->find(input("id"));
		$this->assign('ad',$ad);
		return $this->fetch();
	}

	public function ad_add(){
		if($_POST){
			$update['url']=input("url");
			$update['add_time']=now_time();
			$update['title']=input("title");
			$update['thumb']=input("logo");
			$update['agent_id']=session('agent_id');
			if(input("id")){
				$res=db("agent_advertisement")->where("id",input("id"))->update($update);
			}else{
				$res=db("agent_advertisement")->insert($update);
			}
			if($res){
				return json(['code'=>200,'msg'=>'操作成功']);
			}else{
				return json(['code'=>402,'msg'=>'操作失败']);
			}
		}
		return $this->fetch();
	}

		//鼓励金判断
	private function do_pay($nums,$goods,$agent,&$p_score,&$pay_price,$user_id){
			$user=db('info_user')->field("score")->find($user_id);
			$p_score=$goods['dk_price']*$nums;//抵扣积分
		    if($user['score']>0){//用户积分抵扣
		    	if($p_score&&$user['score']>=$p_score){
		    	 	$pay_price=$pay_price-$p_score;//抵扣后订单价格
		    	}else{
		    		if($p_score<=0){
		    			
		    		}else{
		    			$pay_price=$pay_price-$user['score'];
						$p_score=$user['score'];
		    		}
		    	}
				
			}else{//赠送鼓励金
				$p_score=0;
			}			
	}


		//添加日志
		function add_log($goods_num,$goods_id,$user_id,$agent_id,$emp_id,$sn,$pay_type,$state,$total_price,
		$pay_price,$member_score=0){
			$data['goods_num']=$goods_num;
			$data['goods_id']=$goods_id;
			$data['uid']=$user_id;
			$data['agent_id']=$agent_id;
			$data['clerk_id']=$emp_id;
			$data['order_type']=7;
			$data['message']='单产品下单购买';
			$data['order_sn']=$sn;
			$data['pay_type']=$pay_type;
			$data['state']=$state;
			$data['origin_price']=$total_price;
			$data['balance']=$pay_price;
			$data['add_time']=now_time();
			$data['sy_type']=3;
			$data['member_score']=-$member_score;
			$data['agent_score']=abs($member_score);
			$res=db('log_paylog')->insert($data);
			return $res;
		}


		
		//订单api
		function order_code(){
			header("Content-Type: application/json;charset=utf-8");
			define('REQUEST_METHOD',$_SERVER['REQUEST_METHOD']);
			define('IS_GET',        REQUEST_METHOD =='GET' ? true : false);
			if(!IS_GET){
				$msg=['img'=>'','status'=>'e','msg'=>'数据传输方式错误'];
				exit(json_encode($msg, JSON_UNESCAPED_UNICODE));
			}
			if(isset($_GET['uid'])){
				$data['uid']=$_GET['uid'];
			}
			if(isset($_GET['payment_method'])){
				$data['payment_method']=$_GET['payment_method'];
			}
			if(isset($_GET['order_number'])){
				$data['order_number']=$_GET['order_number'];
			}
			if(isset($_GET['notify_url'])){
				$data['notify_url']=$_GET['notify_url'];
			}
			if(isset($_GET['name'])){
				$data['name']=$_GET['name'];
			}
			if(isset($_GET['amount'])){
				$data['amount']=$_GET['amount'];
			}
			if(isset($_GET['sign'])){
				$data['sign']=$_GET['sign'];
			}
			if(!isset($data['notify_url'])){
				$msg=['img'=>'','status'=>'e','msg'=>'域名回调地址不能为空'];
				return json_encode($msg, JSON_UNESCAPED_UNICODE);
			}
			if(!isset($data['order_number'])){
				$msg=['img'=>'','status'=>'e','msg'=>'订单号不能为空'];
				return json_encode($msg, JSON_UNESCAPED_UNICODE);
			}
			if(!isset($data['amount'])){
				$msg=['img'=>'','status'=>'e','msg'=>'订单金额不能为空'];
				return json_encode($msg, JSON_UNESCAPED_UNICODE);
			}
			if(!is_numeric($data['amount'])){
                $msg=['img'=>'','status'=>'e','msg'=>'金额必须为数字'];
				return json_encode($msg, JSON_UNESCAPED_UNICODE);
			}
			$model =  model('Shopping');
			$arr=$model->setSign($data);
			if($model->chekSign($data)){
				if($model->key($arr)){
					if($model->key($arr)!=-1){
						$str=$model->key($arr);
						$Key_arr=explode('U', $str);
						$url=$this->shop_beiquan_buy($Key_arr[0],$data['amount'],$Key_arr[1]);
						$str=qrcode($url);
                        $data_str=['img'=>$str,'status'=>'S','msg'=>'成功'];
				        exit(json_encode($data_str, JSON_UNESCAPED_UNICODE));
					}else{
						$data_str=['img'=>'','status'=>'e','msg'=>'请勿重复付款'];
						exit(json_encode($data_str, JSON_UNESCAPED_UNICODE));
					}
				}else{
					$data_str=['img'=>'','status'=>'e','msg'=>'该二维码已失效'];
					exit(json_encode($data_str, JSON_UNESCAPED_UNICODE));
				}
			}else{
				  $data_str=['img'=>'','status'=>'e','msg'=>'签名认证失败'];
				  exit(json_encode($data_str, JSON_UNESCAPED_UNICODE));
			}
		}
		function shop_beiquan_buy($agent=null,$amount=null,$order_id=null){
			header("Content-Type: application/json;charset=utf-8");
			$url='https://'.$_SERVER['HTTP_HOST'].'/agent/shop/beiquan_buy?agent_id='.$agent.'&amount='.$amount.'&order_id='.$order_id;
			return $url;
		}
		


		function beiquan_buy(){
			$agent=input('agent_id');
			$amount=input('amount');
			$order_id=input('order_id');
			header("Content-Type: application/json;charset=utf-8");
			if(isset($order_id)){
				$where_order['order_id']=$order_id;
				$order=db('pay_order_api')->where($where_order)->find();
				if($order){
					if($order['is_payment']==2){
						$data_str=['img'=>'','status'=>'e','msg'=>'请勿重复付款'];
						exit(json_encode($data_str, JSON_UNESCAPED_UNICODE));
					}

					if($order['agent_pai_id']){
						$pai_where['api_id']=$order['agent_pai_id'];
						$pay_api=db('pay_api')->where($pai_where)->find();
						if(!$pay_api || $pay_api['is_delete']==2 || $pay_api['is_stop']==2){
							$data_str=['img'=>'','status'=>'e','msg'=>'支付接口异常'];
							exit(json_encode($data_str, JSON_UNESCAPED_UNICODE));
						}
					}

					if($order['agent_id']){
						$agent_pai['api_agent_id']=$order['agent_id'];
						$pay_agent_api=db('pay_agent_api')->where($agent_pai)->find();
						if(!$pay_agent_api || $pay_agent_api['is_delete']==2 || $pay_agent_api['is_valid']==2){
							$data_str=['img'=>'','status'=>'e','msg'=>'二维码已失效'];
							exit(json_encode($data_str, JSON_UNESCAPED_UNICODE));
						}
					}
				}
			}
			
			$type=get_brower_type();//判断是微信还是支付宝打开
			$user=session("info_user");
			
			if(!session('openid')){
				$redirect='https://'.$_SERVER['HTTP_HOST'].'/agent/shop/beiquan_buy?';
				if($type==1){
					$auth_code=input("auth_code");
					$url ='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.config('alipay_appid').'&scope=auth_base&redirect_uri='.urlencode($redirect);
				}else{
					$auth_code=input("code");
					$url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect';
				}
				if(!$auth_code){
					Header("Location: $url");
					exit;
				}
				$openid = '';
				if($type==1){//支付宝openid
					$field="alipay_id";
					$pay_type=3;
					$openid=user_ali_id($auth_code);
				}else{
					//微信openid
					$field="openid";
					$pay_type=2;  
					$openid=user_wx_id($auth_code);
				}

				session('openid',$openid);
				$user_info = db('info_user')->where($field,$openid)->find();
				if($user_info){
					session('info_user', $user_info);
				}else{
					$agent_uid=db('info_agent')->where('id',$agent)->value("user_id");
					$tj_user_info = db('info_user')->where('id',$agent_uid)->find();
						$data['level']			= $tj_user_info['id'];
						$data[$field]			= $openid;
						$data['oem_id']			= $tj_user_info['oem_id'];
						$data['agency_id']		= $tj_user_info['agency_id'];
						$data['agency_id1']		= $tj_user_info['agency_id1'];
						$data['agency_id2']		= $tj_user_info['agency_id2'];
						$data['salesman_id']	= $tj_user_info['salesman_id'];
						$data['tj_pt']			= $tj_user_info['tj_pt'];
						$data['tj_pt1']			= $tj_user_info['tj_pt1'];
						$data['tj_agent']		= $tj_user_info['tj_agent'];
						$data['member_level']	= "ratio_one";
						$data['add_time']		= now_time();
						$data['reg_type']		= 6;//6单商品
						$user_id=Db::name('info_user')->insertGetId($data);
						$cut_user_info = db('info_user')->where('id',$user_id)->find();
						//获取用户信息
						session('info_user', $cut_user_info);
						if($type==2){
							receive();
						}
					   
				}
			}
			if($type==1){
				header("Content-Type: application/json;charset=utf-8");
				$url='https://'.$_SERVER['HTTP_HOST'].'/agent/shop/pay_topay1?agent_id='.$agent.'&amount='.$amount.'&order_id='.$order_id;
				Header("Location: $url");
			}else{
				header("Content-Type: application/json;charset=utf-8");
				$url='https://'.$_SERVER['HTTP_HOST'].'/agent/shop/pay_topay?agent_id='.$agent.'&amount='.$amount.'&order_id='.$order_id;
				Header("Location: $url");
			}
		
		}



	public function topay(){
		$goods_id=input("good_id");
		$chain_id=input("chain_id");
		$goods=db("agent_goods")->field("goods_name,unit,agent_id,dk_price,zs_price,oem_id,sale_price,stock")->find($goods_id);
		$agent=db('info_agent')->find($goods['agent_id']);
		$nums=input('nums');
		//检查商品库存
		if($goods['stock'] < $nums){
			dump('该商品已售罄'); exit;
		}
		$type=get_brower_type();//判断是微信还是支付宝打开
		if($type==1){//支付宝openid
			$field="alipay_id";
			$pay_type=3;
		}elseif($type==2){//微信openid
			$field="openid";
			$pay_type=2;
		}	
		$openid=session('openid');
		$user_id=session("info_user")['id'];
	
		$p_score=0;//抵扣鼓励金
		$price=$goods['sale_price']*$nums;//订单价
		$pay_price=$price;//实际支付价格
		$this->do_pay($nums,$goods,$agent,$p_score,$pay_price,$user_id);
		$sn=order_create_no();
		
		$log_res=$this->add_log($nums,$goods_id,$user_id,$agent['id'],0,$sn,$pay_type,1,$price,
		$pay_price,$p_score);
		if($pay_price==0){//纯积分
			header("Content-Type: application/json;charset=utf-8"); 
			echo '支付成功';exit;
		}
		if($type==1){//支付宝
	        if($agent['is_state']==1){
        		$url=pay_code($agent['cb_no'],$agent['cb_miyao'],$agent['cb_clerk'],$pay_price,1,$sn,'');
				Header("Location: $url");
				exit;
        	}else{
        		header("Content-Type: application/json;charset=utf-8"); 
        		echo '支付失败';exit;
        	}
		}elseif ( $type==2 ) {//微信扫码
				 if($agent['is_state']==1){
        			$url=pay_code($agent['cb_no'],$agent['cb_miyao'],$agent['cb_clerk'],$pay_price,2,$sn,'');
					Header("Location: $url");
					exit;
	        	
	        	}else{
					header("Content-Type: application/json;charset=utf-8");
	        		echo '支付失败';exit;
	        	}
		}    
	
	}

	public function pay_topay(){
		
	    $agent_id=input('agent_id');
		$agent=db('info_agent')->find($agent_id);
		$type=get_brower_type();//判断是微信还是支付宝打开
		if($type==1){//支付宝openid
			$field="alipay_id";
			$pay_type=3;
		}elseif($type==2){//微信openid
			$field="openid";
			$pay_type=2;
		}	
		$openid=session('openid');
		$user_id=session("info_user")['id'];
		$p_score=0;//抵扣鼓励金
		$price=input('amount');//订单价
		$pay_price=$price;//实际支付价格
		// $this->do_pay(1,$agent,$p_score,$pay_price,$user_id);
		$sn=order_create_no();
        $order_id=input('order_id');
		if($order_id){
			$where['order_id'] = $order_id;
			$data['sb_no'] = $sn;
			$data['sb_time'] = now_time();
			$result=Db::table('pay_order_api')->where($where)->update($data);
		}
		$log_res=$this->add_log(1,'',$user_id, $agent_id,0,$sn,$pay_type,1,$price,
		$pay_price,$p_score);
		if($pay_price==0){//纯积分
			header("Content-Type: application/json;charset=utf-8"); 
			echo '支付成功';exit;
		}
		if($type==1){//支付宝
	        if($agent['is_state']==1){
        		$url=pay_code($agent['cb_no'],$agent['cb_miyao'],$agent['cb_clerk'],$pay_price,1,$sn,'');
				Header("Location: $url");
				exit;
        	}else{
        		header("Content-Type: application/json;charset=utf-8");
        		echo '支付失败';exit;
        	}
		}elseif ( $type==2 ) {//微信扫码
				 if($agent['is_state']==1){
        			$url=pay_code($agent['cb_no'],$agent['cb_miyao'],$agent['cb_clerk'],$pay_price,2,$sn,'');
					Header("Location: $url");
					exit;
	        	
	        	}else{
					header("Content-Type: application/json;charset=utf-8");
	        		echo '支付失败';exit;
	        	}
		}    
	
	}

	public function topay1(){
		$goods_id=input("good_id");
		$chain_id=input("chain_id");
		$goods=db("agent_goods")->field("goods_name,unit,agent_id,dk_price,zs_price,oem_id,sale_price,stock")->find($goods_id);
		$agent=db('info_agent')->find($goods['agent_id']);
		$nums=input('nums');
		//检查商品库存
		if($goods['stock'] < $nums){
			dump('该商品已售罄'); exit;
		}
		$type=get_brower_type();//判断是微信还是支付宝打开
		
		$field="alipay_id";
		$pay_type=3;
		
		$openid=session('openid');
		$user_id=session("info_user")['id'];
	
		$p_score=0;//抵扣鼓励金
		$price=$goods['sale_price']*$nums;//订单价
		$pay_price=$price;//实际支付价格
		$sn=order_create_no();
		$log_res=$this->add_log($nums,$goods_id,$user_id,$agent['id'],0,$sn,$pay_type,1,$price,
		$pay_price,$p_score);

        if($agent['is_state']==1){
    		$url=pay_code($agent['cb_no'],$agent['cb_miyao'],$agent['cb_clerk'],$pay_price,1,$sn,'');
			Header("Location: $url");
			exit;
    	}else{
    		header("Content-type: text/html; charset=utf-8"); 
    		echo '支付失败';exit;
    	}
		
	
	}

	public function pay_topay1(){
		header("Content-Type: application/json;charset=utf-8");
		$agent_id=input('agent_id');
		$agent=db('info_agent')->find($agent_id);
		$type=get_brower_type();//判断是微信还是支付宝打开
		$field="alipay_id";
		$pay_type=3;
		$openid=session('openid');
		$user_id=session("info_user")['id'];
		$p_score=0;//抵扣鼓励金
		$pay_price=input('amount');//实际支付价格
		$sn=order_create_no();
		$order_id=input('order_id');
		if($order_id){
			$where['order_id'] = $order_id;
			$data['sb_no'] = $sn;
			$data['sb_time'] = $sn;
			$result=Db::table('pay_order_api')->where($where)->update($data);
		}
		$log_res=$this->add_log(1,'',$user_id,$agent_id,0,$sn,$pay_type,1,$pay_price,
		$pay_price,$p_score);

        if($agent['is_state']==1){
    		$url=pay_code($agent['cb_no'],$agent['cb_miyao'],$agent['cb_clerk'],$pay_price,1,$sn,'');
			Header("Location: $url");
			exit;
    	}else{
    		header("Content-type: text/html; charset=utf-8"); 
    		echo '支付失败';exit;
    	}
		
	
	}
	//商品管理
	public function goods_manage()
    {
    	if(request()->isPost()){
    		
    		$param=input('post.');
			
			if(!empty($param['goods_no']))$where['a.goods_no'] = ['like','%'.$param['goods_no'].'%'];
			
			if(!empty($param['goods_name']))$where['a.goods_name'] = ['like','%'.$param['goods_name'].'%'];
			
			if(!empty($param['begin_time']) && !empty($param['end_time'])){
				$where['a.addtime'] = ['between time',[$param['begin_time'],$param['end_time']]];
			}
    	}  
		$type_id=0;
		if(input('type_id')){
			$where['a.trade_id'] = input('type_id');	
			$type_id=input('type_id');
		}
		$this->assign('type_id',$type_id);
		
		$where['a.agent_id'] = session('agent_id');
		$where['a.goods_state'] = ['<>',3];
    	
		//获取当前店铺商品
		$goods_list = db('agent_goods')
						->alias('a')
						->field('a.id as goods_id,a.cost_price,a.goods_no,a.goods_name,a.sale_price,a.zs_price,a.goods_state,a.is_recommend,a.dk_price,a.addtime,b.id,b.type_name,a.stock')
						->join('agent_type b','a.trade_id = b.id','left')
						->where($where)
						->order('a.addtime desc')
						->paginate(15,false,['query'=>request()->param()]);
		
		$this->assign('goods_name',input('goods_name'));
		$this->assign('goods_no',input('goods_no'));
		$this->assign('begin_time',input('begin_time'));
		$this->assign('end_time',input('end_time'));
		$this->assign('goods_list',$goods_list);
		$costs = db('agent_goods')->alias('a')->where($where)->sum("cost_price");
		$this->assign('costs',$costs);
		//获取商品分类类型
		$goods_type = db('agent_type')->where('agent_id',session('agent_id'))->select();
		$this->assign('goods_type',$goods_type);
		$this->assign('empty','<span class="empty" >没有数据</span>');
    	return $this->fetch();
    }

	//商品管理导出
    public function exportout_dc(){
		$param=input();
		if(!empty($param['begin_time']) && !empty($param['end_time'])){
			$where['a.addtime'] = ['between time',[$param['begin_time'],$param['end_time']]];
		}
		if(!empty($param['goods_no']))$where['a.goods_no'] = $param['goods_no'];
		if(!empty($param['goods_name']))$where['a.goods_name'] = $param['goods_name'];
		if(!empty($param['type_id']))$where['a.trade_id'] = $param['type_id'];
			
		$where['a.agent_id'] = session('agent_id');
		$where['a.goods_state'] = ['<>',3];
    	
		//获取当前店铺商品
		$list = db('agent_goods')
				->alias('a')
				->field('a.content,a.is_recommend,a.cost_price,a.chainstore_id,a.id as goods_id,a.goods_no,a.goods_name,a.sale_price,a.zs_price,a.goods_state,a.is_recommend,a.dk_price,a.addtime,b.id,b.type_name,a.stock,c.store_name')
				->join('agent_type b','a.trade_id = b.id','left')
				->join('agent_store c','a.chainstore_id = c.id and a.agent_id = c.agent_id','left')
				->where($where)
				->order('a.addtime desc')
				->select();	
				
		$str ="id,商品编号,商品名称,商品分类,成本价,市场价,赠送鼓励金,会员价,库存,是否设为推荐1否2是,商品描述,门店编号"."\n";
        $str = iconv('utf-8','gbk',$str);
        foreach($list as $k=>$row){
        	$no= sprintf("%.0f", $row['goods_no']);
        	$goods_id= iconv('utf-8','gbk',$row['goods_id']);
        	$goods_no= iconv('utf-8','gbk',$no."\t");
			$goods_name = iconv('utf-8','gbk',$row['goods_name'].'	');  
			$type_name = iconv('utf-8','gbk',$row['type_name'].'	');
			$cost_price=iconv('utf-8','gbk',$row['cost_price']);
			$price = iconv('utf-8','gbk',$row['sale_price']);
			$zs_price = iconv('utf-8','gbk',$row['zs_price']);
			$hyprice = iconv('utf-8','gbk',$row['sale_price']-$row['dk_price']);
			$stock = iconv('utf-8','gbk',$row['stock']);
			$istj = iconv('utf-8','gbk',$row['is_recommend']);
			//$content=iconv('utf-8','gbk',$row['content']);
			$store_name = iconv('utf-8','gbk',$row['chainstore_id']);
			$str .= $goods_id.",".$goods_no.",".$goods_name.",".$type_name.",".$cost_price.",".$price.",".$zs_price.",".$hyprice.",".$stock.",".$istj.",".$store_name.","."\n"; //用引文逗号分开 
        } 

	  	$filename ='商品列表.csv';   //设置文件名  
    	
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str; 
        exit;
	}
	
	//入库日志
	public function rukulogs(){
		$where['o.agent_id']=session("agent_id");
		$list = db('agent_ruku')->alias('o')
    					->join('agent_goods g','o.goods_id=g.id',"left")
    					->where($where)
    					->field("o.*,g.goods_name,g.goods_no")
    					->order('o.add_time desc')
    					->paginate(10,false,['query'=>request()->param()]);
		$this->assign("list",$list);
		$this->assign('empty','<span class="empty">没有数据</span>');	
		return $this->fetch();
	}
	public function set_yj(){
		$res=db('info_agent')->where('id',session('agent_id'))->update(['yj_value'=>input('value')]);
		if($res){
			return json(['code'=>200,'msg'=>'设置成功']);
		}
		return json(['code'=>400,'msg'=>'设置失败']);
	}
	//入库日志
	public function yj_list(){
		$where['agent_id']=session('agent_id');
		$yj=db("info_agent")->where("id",session('agent_id'))->value("yj_value");
		$this->assign('yj',$yj);
		if(input('goods_no')){
			$where['goods_no']=["like","%".input('goods_no')."%"];
		}
		$where['stock']=["<=",$yj];
		$goods=db('agent_goods')->where($where)->field("id,addtime,goods_name,goods_no,stock")
		->order('addtime desc')
    	->paginate(10,false,['query'=>request()->param()]);
		$this->assign('list',$goods);
		$this->assign('empty','<span class="empty">没有数据</span>');	
		return $this->fetch();
	}
	//入库操作
	public function ruku(){
		if($_POST){
			$up['stock']=['exp',"stock+".input('stock')];
			$res=db('agent_goods')->where("id",input('id'))->update($up);
			if($res){
				$data['add_time']=now_time();
				$data['goods_id']=input("id");
				$data['agent_id']=session("agent_id");
				$data['memo']=input('memo');
				$data['nums']=input('stock');
				$res=db('agent_ruku')->insert($data);
				if($res){
					return json(['code'=>200,'msg'=>'操作成功']);
				}
				return json(['code'=>400,'msg'=>'操作失败']);
			}
			return json(['code'=>400,'msg'=>'操作失败']);
		}
		$good=db('agent_goods')->where("id",input('goods_id'))->field("id,goods_no,goods_name,stock")->find();
		$this->assign('good',$good);
		return $this->fetch();
	}
	//添加商品
    public function goods_add(){
    	//获取当前商家信息
    	$agent_id = session('agent_id');
		
    	if(request()->isPost()){
    		$param=input('post.');
			$param['addtime'] 	= now_time();
			$param['agent_id'] 	= session('agent_id');
			$param['oem_id']  	= session('oem_id');
			$agent_goods = new GoodsModel();
			$param['goods_no']=trim($param['goods_no']);
			$param['sale_price'] = $param['cost_price'];
			$res = $agent_goods->allowField(true)->save($param);
			if($res){
				return json(['code'=>200,'msg'=>'添加成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'添加失败']);
			}
			
    	}
		//获取平台分类
		$platform_type = Db::table('sys_platform_type')->select();
		//1级分类
		$platform_1 = array();
		//2级分类
		$platform_2 = array();
		foreach($platform_type as $key=>$values){
			if($values['pid'] == 0){
				$platform_1[] = $values;
			}else{
				$platform_2[$values['pid']][] = $values;
			}
		}
		$this->assign('platform_1',$platform_1);
		$this->assign('platform_2',$platform_2);
		//获取商家分类
		$agent_type = Db::table('agent_type')->where('agent_id',$agent_id)->select();
		$this->assign('agent_type',$agent_type);
		
		
    	return $this->fetch();
    }

	//修改商品
    public function goods_edit(){
    	
		if(request()->isPost()){
			$param=input('post.');
			$agent_goods = new GoodsModel();
			$param['sale_price'] = $param['cost_price'];
			$res = $agent_goods->allowField(true)->save($param,$param['id']);
			
			if($res){
				return json(['code'=>200,'msg'=>'修改成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
			
		}
    	$goods_id = input('goods_id');
		$goods_info = db('agent_goods')
						->alias('a')
						->join('agent_type b','a.trade_id = b.id','left')
						->where('a.id',$goods_id)
						->find();
		if($goods_info){
			//商品信息
			$goods_info['content'] = html_entity_decode($goods_info['content']);
			$goods_info['goods_id'] = $goods_id;
			$this->assign('goods_info',$goods_info);
			
			//获取平台分类
			$platform_type = Db::table('sys_platform_type')->select();
			//1级分类
			$platform_1 = array();
			//2级分类
			$platform_2 = array();
			foreach($platform_type as $key=>$values){
				if($values['pid'] == 0){
					$platform_1[] = $values;
				}else{
					$platform_2[$values['pid']][] = $values;
				}
			}
			$this->assign('platform_1',$platform_1);
			$this->assign('platform_2',$platform_2);
			//获取商家分类
			$agent_type = Db::table('agent_type')->where('agent_id',session('agent_id'))->select();
			$this->assign('agent_type',$agent_type);
			
			
		}else{
			$this->error('商品不存在');
		}
		
		return $this->fetch();
    }

	//删除商品
	function del_goods(){
		
		$id = input('goods_id');
		
		$res = db('agent_goods')->where('id',$id)->update(['goods_state'=>3]);
		if($res){
			$this->success('删除成功', url('agent/shop/goods_manage'));
		}else{
			$this->error('删除失败');
		}
		
	}




    //商品分类
	public function goods_type()
    {
    	$agentid = session('agent_id');
    	$list = Db::table('agent_type')->where('agent_id',$agentid)->order('id desc')->paginate(10,false,['query'=>request()->param()]);
        $this->assign('list',$list);
		$this->assign('empty','<span class="empty">没有数据</span>');	
    	return $this->fetch();
    }
	
	
    public function goods_type_add()
    {
    	$agentid = session('agent_id');
    	$oemid = session('oem_id');
    	if($_POST){
    		$data['logo']=$_POST['logo'];
            $data['type_name']=$_POST['type_name'];
            $data['agent_id']=$agentid;
            $data['oem_id']=$oemid;
            $result=Db::table('agent_type')->insert($data);
            if($result){
			return json(['code'=>200,'msg'=>'成功']);
	        }else{
	       		return json(['code'=>402,'msg'=>'失败']);
	        }
        }
    	
    	return $this->fetch();
    }
    public function goods_type_update()
    {
    	$id = input('id');
    	if($_POST){
    		$data['logo']=$_POST['logo'];
    		$data['type_name']=$_POST['type_name'];
            $result=Db::table('agent_type')->where('id',$id)->update($data);;
            if($result){
				return json(['code'=>200,'msg'=>'成功']);
	        }else{
	       		return json(['code'=>402,'msg'=>'失败']);
	        }
        }
        $list = Db::table('agent_type')->where('id',$id)->find();
        $this->assign('list',$list);
    	return $this->fetch();
    }
    public function goods_type_del()
    {
    	$id = input("id");
    	$res=db('agent_goods')->where('trade_id',$id)->find();
    	if($res){
			return json(['code'=>408,'msg'=>'该类有商品，不能删除']);
        }else{
       		$result = Db::table('agent_type')->where('id',$id)->delete();
       		if($result){
			return json(['code'=>200,'msg'=>'成功']);
	        }else{
	       		return json(['code'=>402,'msg'=>'失败']);
	        }
        }
    	
        
    	
    }
	//核销订单
	public function confirm(){
		$where['agent_id']=session('agent_id');
		$where['id']=input("id");
		$res=db('agent_syorder')->where($where)->update(["status"=>5]);
		if($res){
			return json(['code'=>200,'msg'=>'操作成功']);
		}else{
			return json(['code'=>400,'msg'=>'操作失败']);
		}
	}
	//核销订单
	public function close(){
		$where['agent_id']=session('agent_id');
		$where['id']=input("id");
		$res=db('agent_syorder')->where($where)->update(["status"=>3]);
		if($res){
			return json(['code'=>200,'msg'=>'操作成功']);
		}else{
			return json(['code'=>400,'msg'=>'操作失败']);
		}
	}
    //订单管理
	public function goods_order()
    {
    	$where['o.agent_id']= session('agent_id');
		$where['o.type']=4;	
		if(input('sn')){
			$where['o.sn']=input('sn');
			$this->assign('sn',input('sn'));
		}else{
			$this->assign('sn',0);
		}
		if(input('status')){
			$where['o.status']=input("status");
			$this->assign('status',input('status'));
		}else{
			$this->assign('status',0);
		}
    	$list = Db::name('agent_syorder')
    					->alias('o')
    					->join("info_user u","o.user_id=u.id","left")
    					->join('agent_goods g','o.goods_id=g.id',"left")
    					->where($where)
    					->field("o.*,u.mobile,g.goods_name")
    					->order('o.add_time desc')
    					->paginate(10,false,['query'=>request()->param()]);
		
		$this->assign('begin_time',input('begin_time'));
		$this->assign('end_time',input('end_time'));
        $this->assign('list',$list);
    	return $this->fetch();
    }
    //评价管理
	public function evaluate()
    {
    	$list = Db::name('goods_comment')->where('agent_id',session('agent_id'))->order('add_time desc')->paginate(15);
        $this->assign('list',$list);
    	return $this->fetch();
    }
    
    //广告管理
	public function advertisement()
    {
    	$list=db("agent_advertisement")->where("agent_id",session('agent_id'))->select();
        $this->assign('list',$list);
		$this->assign('empty','<span class="empty">没有数据</span>');
    	return $this->fetch();
    }
    //是否上架
	public function shangjia()
    {
    	$data['goods_state'] = input("goods_state");
    	$res = Db::name('agent_goods')->where('id',input("id"))->update($data);
        if($res){
			return json(['code'=>200,'msg'=>'修改成功']);
		}else{
			return json(['code'=>402,'msg'=>'修改失败']);
		}
    }
    
	//是否推荐
	public function tuijian()
    {
    	$data['is_recommend'] = input("is_recommend");
    	$res = Db::name('agent_goods')->where('id',input("id"))->update($data);
        if($res){
			return json(['code'=>200,'msg'=>'修改成功']);
		}else{
			return json(['code'=>402,'msg'=>'修改失败']);
		}
    }
    
    //单商品打印开关
	public function open_prt(){
		$agentid = session('agent_id');
    	$data['paid']=input('paid');
    	
        $result=Db::table('agent_prt')->where('agent_id',$agentid)->update($data);
        if($result){
			return json(['code'=>200,'msg'=>'成功']);
        }else{
       		return json(['code'=>402,'msg'=>'失败']);
        }
	}
	
	//门店码打印开关
	public function store_switch(){
		$agentid = session('agent_id');
    	$data['store_switch']=input('store_switch');
    	
        $result=Db::table('agent_prt')->where('agent_id',$agentid)->update($data);
        if($result){
			return json(['code'=>200,'msg'=>'成功']);
        }else{
       		return json(['code'=>402,'msg'=>'失败']);
        }
	}
}
